package repository

import (
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-common/utils/queryWrapper"
)

type ITransfeeFreeRepository interface {
	CreateBatch(db *gorm.DB, transcityFrees []*model.TransfeeFree) error
	DeleteBatch(db *gorm.DB, transcityFrees []*model.TransfeeFree) error
	Find(db *gorm.DB, pair *queryWrapper.WherePair) (transfeeFrees []*model.TransfeeFree, err error)
}

type TransfeeFreeRepository struct {
}

func NewTransfeeFreeRepository() ITransfeeFreeRepository {
	return &TransfeeFreeRepository{}
}

func (r *TransfeeFreeRepository) CreateBatch(db *gorm.DB, transcityFrees []*model.TransfeeFree) error {
	return db.Create(&transcityFrees).Error
}

func (r *TransfeeFreeRepository) DeleteBatch(db *gorm.DB, transcityFrees []*model.TransfeeFree) (err error) {
	for _, transcityFree := range transcityFrees {
		if err := db.Delete(&model.TransfeeFree{}, transcityFree.TransfeeFreeId).Error; err != nil {
			return err
		}

		if len(transcityFree.FreeCityList) > 0 {
			err = db.Delete(&transcityFree.FreeCityList).Error
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func (r *TransfeeFreeRepository) Find(db *gorm.DB, pair *queryWrapper.WherePair) (transfeeFrees []*model.TransfeeFree, err error) {
	tx := db.Preload("FreeCityList").Model(&model.TransfeeFree{})
	return transfeeFrees, queryWrapper.ReuseWherePair(tx, pair).Find(&transfeeFrees).Error
}
